package org.apselex;

/*
 * Copyright (c) 2008 Evan Williams
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

import nu.xom.Document;
import nu.xom.Element;

import org.apache.log4j.Logger;
import org.apselex.model.ModelElement;
import org.apselex.providers.DataProvider;
import org.apselex.providers.XmlTranslator;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;

import apselmodel.Activator;

public class ExportJob extends Job {

	private Element root;
	private DataProvider data;
	private Object[] elements;

	private static Logger logger = Logger.getLogger(ExportJob.class);

	public ExportJob(String name, Element eRoot,
			DataProvider data) {
		super(name);
		this.root = eRoot;
		this.data = data;
		Object[] elements = data.getElements();

		this.elements = elements;

	}

	@Override
	protected IStatus run(IProgressMonitor monitor) {
		logger.debug("run - start");

		int iSize = elements.length;
		monitor.beginTask("process", iSize);
		for (Object o : elements) {
			if (o instanceof ModelElement) {
				ModelElement me = (ModelElement) o;
				me.setMetadata(data.getMetaData(me.getId()));
				me.setTags(data.getTags(me.getId()));
				Element e = XmlTranslator.transform((ModelElement) o);
				root.appendChild(e);
				logger.debug("EEE element is:" + e);

				// provide a delay - to simulate a big workload!!
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}
			monitor.worked(1);
		}
		Document doc = root.getDocument();
		XmlTranslator.output(doc);

		logger.debug("run - stop");

		return Status.OK_STATUS;
	}

}
